//
//  ZHttpClient.m
//  ZFramework
//
//  Created by liuchengbin on 15/5/9.
//  Copyright (c) 2015年 liuchengbin. All rights reserved.
//

#import "ZHttpClient.h"
#import "ZHttpCache.h"
#import "ZGlobal.h"
#import "ZToastManager.h"
@interface ZHttpClient()
{
}
@end

@implementation ZHttpClient

#pragma mark - request
- (void)requestWithURL:(NSString *)url
                 paras:(NSDictionary *)parasDict
                  type:(ZHttpResponseType)type
            allowFetchCache:(BOOL)allowFetchCache
               success:(void(^)(AFHTTPRequestOperation* operation, NSObject *resultObject))success
               failure:(void(^)(NSError *requestErr))failure
{
    int allowSaveCache = [[NSNumber numberWithInt:ZHttpCacheDisk] intValue];
    // 加入允许读缓存
    if (allowFetchCache) {
        // check cache
        id cacheObj = [[ZHttpCache sharedInstance]fetchResponseForUrl:url byParam:parasDict];
        if (cacheObj) {
            dispatch_async(dispatch_get_main_queue(), ^{
                success(nil,cacheObj);
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            });
        }
    }
    
    

    // 检查是否是xml解析
    // 已指定何种格式解析，无需重复相同实例化，否则http多线程会引起内存问题
    if (type == ZHttpResponseType_XML) {
        
        if (![self.responseSerializer isMemberOfClass:[AFXMLParserResponseSerializer class]])
        {
            AFXMLParserResponseSerializer *xmlParserSerializer = [[AFXMLParserResponseSerializer alloc] init];
            self.responseSerializer = xmlParserSerializer;
        }
    }
    else if (type == ZHttpResponseType_Json) {
        if(![self.responseSerializer isMemberOfClass:[AFJSONResponseSerializer class]])
        {
            AFJSONResponseSerializer *jsonParserSerializer = [[AFJSONResponseSerializer alloc] init];
            self.responseSerializer = jsonParserSerializer;
        }
    }
    else {
        if (![self.responseSerializer isMemberOfClass:[AFHTTPResponseSerializer class]])
        {
            AFHTTPResponseSerializer *httpParserSerializer = [[AFHTTPResponseSerializer alloc] init];
            self.responseSerializer = httpParserSerializer;
        }
    }

    NSMutableDictionary *transferParas = [NSMutableDictionary dictionaryWithDictionary:parasDict];
    // 检查BaseURL
    NSString *requestURL = url;
    self.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
//    DLog(@"url:%@\r\n", url);
    // 开始请求
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    __weak typeof(self) wSelf = self;
    
    [self POST:requestURL parameters:transferParas success:^(AFHTTPRequestOperation *operation, id responseObject){
        
            if(type == ZHttpResponseType_Common)
            {
                responseObject = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            }
            else if (type == ZHttpResponseType_JqueryJson)
            {
                NSError* error = nil;
                NSString* result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSString* r = nil;
                NSRange r1 = [result rangeOfString:@"("];
                if (r1.location == 0)
                {
                    r = [result substringFromIndex:1];
                    r = [[r substringToIndex:r.length - 1] stringByReplacingOccurrencesOfString:@"'" withString:@"\""];
                }
                else if(r1.length > 0)
                {
                    r = [result substringFromIndex:r1.location+1];
                    NSRange r2 = [r rangeOfString:@")"];
                    r = [[r substringToIndex:r2.location] stringByReplacingOccurrencesOfString:@"'" withString:@"\""];
                }
                else
                {
                    r = [result stringByReplacingOccurrencesOfString:@"'" withString:@"\""];
                }
                responseObject = [NSJSONSerialization JSONObjectWithData:[r dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];

            }
        
    
            if (allowSaveCache == ZHttpCacheMemory || allowSaveCache == ZHttpCacheDisk) {
                [[ZHttpCache sharedInstance] storeResponse:responseObject forUrl:requestURL byParam:transferParas toDisk:allowSaveCache == ZHttpCacheMemory? NO:YES];
            }
      
            success(operation, responseObject);
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            failure(error);
            [wSelf reach];
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        }];
}
-(void)cancel
{
    [[self operationQueue] cancelAllOperations];
}
- (void)reach
{
    /**
     AFNetworkReachabilityStatusUnknown          = -1,  // 未知
     AFNetworkReachabilityStatusNotReachable     = 0,   // 无连接
     AFNetworkReachabilityStatusReachableViaWWAN = 1,   // 3G 花钱
     AFNetworkReachabilityStatusReachableViaWiFi = 2,   // 局域网络,不花钱
     */
    // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus<=0)
        {
            [[ZToastManager ShardInstance] showtoast:@"亲，网络不给力哦!"];
        }
    }];
}
- (void)iconImagesWithURL:(NSString *)url
                 paras:(NSDictionary *)parasDict
                 images:(NSArray*)images
               success:(void(^)(AFHTTPRequestOperation* operation, NSObject *resultObject))success
               failure:(void(^)(NSError *requestErr))failure
        uploadProgress:(void(^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))uploadProgress
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    AFHTTPRequestOperation *operation = [manager POST:url
                                           parameters:parasDict
                            constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                                
                                if (images.count > 0) {
                                    NSObject *firstObj = [images objectAtIndex:0];
                                    if ([firstObj isKindOfClass:[UIImage class]]) {     // 图片
                                        for(NSInteger i=0; i<images.count; i++) {
                                            UIImage *eachImg = [images objectAtIndex:i];
                                            NSData *data;
                                            //以下这两步都是比较耗时的操作，最好开一个HUD提示用户，这样体验会好些，不至于阻塞界面
                                            if (UIImagePNGRepresentation(eachImg) == nil) {
                                                //将图片转换为JPG格式的二进制数据
                                                data = UIImageJPEGRepresentation(eachImg, 1);
                                            } else {
                                                //将图片转换为PNG格式的二进制数据
                                                data = UIImagePNGRepresentation(eachImg);
                                            }
                                            
                                            srand((unsigned)time(0));  //不加这句每次产生的随机数不变
                                            int iRnd= rand() ;//% 50000;
                                            NSString * strId = [NSString stringWithFormat:@"%d-%ld-yike.com.png", iRnd, time(0)];
                                            
                                            [formData appendPartWithFileData:data name:@"upfile" fileName:strId mimeType:@"image/png"];
                                        }
                                    }else {         // 视频
                                        //                                        ALAsset *asset = [mediaDatas objectAtIndexSafe:0];
                                        //                                        NBLog(@"asset=%@, representation=%@, url=%@", asset, [asset defaultRepresentation], [asset defaultRepresentation].url);
                                        //                                        if (asset != nil) {
                                        //                                            NSString *videoPath = [NSDocumentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.mov", 0]];    // 这里直接强制写一个即可，之前计划是用i++来区分不明视频
                                        //                                            NSURL *url = [NSURL fileURLWithPath:videoPath];
                                        //                                            NSError *theErro = nil;
                                        //                                            BOOL exportResult = [asset exportDataToURL:url error:&theErro];
                                        //                                            NBLog(@"exportResult=%@", exportResult?@"YES":@"NO");
                                        //
                                        //                                            NSData *videoData = [NSData dataWithContentsOfURL:url];
                                        //                                            [formData appendPartWithFileData:videoData name:@"video1" fileName:@"video1.mov" mimeType:@"video/quicktime"];
                                        //                                            NBLog(@"method 2");
                                        //                                        }
                                    }
                                }
                            } success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                responseObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
//
                                success(operation, responseObject);
                            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                failure(error);
                            }];
    
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        uploadProgress(bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
    }];
}

- (void)uploadImageWithURL:(NSString *)url
                      paras:(NSDictionary *)parasDict
                     images:(NSArray*)images
                    success:(void(^)(AFHTTPRequestOperation* operation, NSObject *resultObject))success
                    failure:(void(^)(NSError *requestErr))failure
             uploadProgress:(void(^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))uploadProgress
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    AFHTTPRequestOperation *operation = [manager POST:url
                                           parameters:parasDict
                            constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                                
                                if (images.count > 0) {
                                    NSObject *firstObj = [images objectAtIndex:0];
                                    if ([firstObj isKindOfClass:[UIImage class]]) {     // 图片
                                        for(NSInteger i=0; i<images.count; i++) {
                                            id eachImg = [images objectAtIndex:i];
                                            if (eachImg && [eachImg isKindOfClass:[UIImage class]]) {
                                                UIImage *eachImg = [images objectAtIndex:i];
                                                NSData *data = UIImageJPEGRepresentation(eachImg , 0.75);
                                                
                                                srand((unsigned)time(0));  //不加这句每次产生的随机数不变
                                                int iRnd= rand() ;//% 50000;
                                                NSString * strId = [NSString stringWithFormat:@"%d-%ld-yike.com.jpg", iRnd, time(0)];
                                                NSString *name = [NSString stringWithFormat:@"upfile%ld",(long)i];
                                                [formData appendPartWithFileData:data name:name fileName:strId mimeType:@"image/jpg"];
                                            }
                                           
                                        }
                                    }
                                }
                            } success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                responseObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                                //
                                success(operation, responseObject);
                            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                failure(error);
                            }];
    
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        uploadProgress(bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
    }];
}

- (void)uploadImageWithURL:(NSString *)url
                     paras:(NSDictionary *)parasDict
                     cover:(UIImage*)cover
                    images:(NSArray*)images
                   success:(void(^)(AFHTTPRequestOperation* operation, NSObject *resultObject))success
                   failure:(void(^)(NSError *requestErr))failure
            uploadProgress:(void(^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))uploadProgress
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    AFHTTPRequestOperation *operation = [manager POST:url
                                           parameters:parasDict
                            constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                                if (cover) {
                                    NSData *data;
                                    //以下这两步都是比较耗时的操作，最好开一个HUD提示用户，这样体验会好些，不至于阻塞界面
                                    if (UIImagePNGRepresentation(cover) == nil) {
                                        //将图片转换为JPG格式的二进制数据
                                        data = UIImageJPEGRepresentation(cover, 1);
                                    } else {
                                        //将图片转换为PNG格式的二进制数据
                                        data = UIImagePNGRepresentation(cover);
                                    }
                                    
                                    srand((unsigned)time(0));  //不加这句每次产生的随机数不变
                                    int iRnd= rand() ;//% 50000;
                                    NSString * strId = [NSString stringWithFormat:@"%d-%ld-yike.com.png", iRnd, time(0)];
                                    [formData appendPartWithFileData:data name:@"topfile" fileName:strId mimeType:@"image/png"];
                                }
                                
                                if (images.count > 0) {
                                    NSObject *firstObj = [images objectAtIndex:0];
                                    if ([firstObj isKindOfClass:[UIImage class]]) {     // 图片
                                        for(NSInteger i=0; i<images.count; i++) {
                                            id eachImg = [images objectAtIndex:i];
                                            if (eachImg && [eachImg isKindOfClass:[UIImage class]]) {
                                                UIImage *eachImg = [images objectAtIndex:i];
                                                NSData *data;
                                                //以下这两步都是比较耗时的操作，最好开一个HUD提示用户，这样体验会好些，不至于阻塞界面
                                                if (UIImagePNGRepresentation(eachImg) == nil) {
                                                    //将图片转换为JPG格式的二进制数据
                                                    data = UIImageJPEGRepresentation(eachImg, 1);
                                                } else {
                                                    //将图片转换为PNG格式的二进制数据
                                                    data = UIImagePNGRepresentation(eachImg);
                                                }
                                                
                                                srand((unsigned)time(0));  //不加这句每次产生的随机数不变
                                                int iRnd= rand() ;//% 50000;
                                                NSString * strId = [NSString stringWithFormat:@"%d-%ld-yike.com.png", iRnd, time(0)];
                                                NSString *name = [NSString stringWithFormat:@"upfile%ld",(long)i];
                                                [formData appendPartWithFileData:data name:name fileName:strId mimeType:@"image/png"];
                                            }
                                            
                                        }
                                    }
                                }
                            } success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                responseObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                                //
                                success(operation, responseObject);
                            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                failure(error);
                            }];
    
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        uploadProgress(bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
    }];
}
@end
